package com.zzy.chapter4.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.zzy.chapter4.decorator.OrderServiceDecorator;
import com.zzy.chapter4.pojo.Order;
import com.zzy.chapter4.service.OrderService;
import com.zzy.chapter4.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    //@Value("${service.level}")
    private int serviceLevel;

    @Autowired
    private OrderServiceDecorator orderService;

    @PostMapping("/create")
    public Order createOrder(@RequestParam String productId) {
        return orderService.createOrder(productId);
    }

    @PostMapping("/pay")
    public String payOrder(@RequestParam String orderId,
                           @RequestParam Float price,
                           @RequestParam Integer payType) {
        return orderService.getPayUrl(orderId, price, payType);
    }

    @PostMapping("/send")
    public Order sendOrder(@RequestParam String orderId) {
        return orderService.send(orderId);
    }

    @PostMapping("/receive")
    public Order receiveOrder(@RequestParam String orderId) {
        return orderService.receive(orderId);
    }

    @PostMapping("/alipaycallback")
    public String alipayCallback(@RequestBody HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        // 获取回调信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParameterMap = request.getParameterMap();
        for (Iterator<String> iter = requestParameterMap.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParameterMap.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.ISO_8859_1);
            params.put(name, valueStr);
        }
        // 验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, Constants.ALIPAY_PUBLIC_KEY, "UTF-8", Constants.SIGN_TYPE);
        // 确认是支付宝回调
        if (signVerified) {
            String out_trade_no = new String(params.get("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            String trade_no = new String(params.get("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            float total_amount = Float.parseFloat(new String(params.get("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
//            Order order = orderService.payOrder(out_trade_no);
            Order order = orderService.decoratorPay(out_trade_no, serviceLevel, total_amount);
            return "支付成功页面跳转，当前订单为：" + order;
        } else {
            throw new UnsupportedOperationException("回调失败！");
        }
    }

    @PostMapping("/friendPay")
    public void friendPay(String sourceCustomer, String orderId, String targetCustomer, String payResult, String role) {
        orderService.friendPay(sourceCustomer, orderId, targetCustomer, payResult, role);
    }
}
